var IE = /*@cc_on!@*/false;
// Waiting
function login(userName, password)
{
   var content = document.getElementById("content");
   var sUrl = ContextPath + "/ProjectList.do?action=login";
   // Define the callback object for Connection Manager that will set the body of our content area when the content has loaded
   var callback =
   {
      success : function(o)
      {
         var response = o.responseText;
         YAHOO.virtium.container.wait.hide();
         if(response == "success")
         {
        	// location.reload(true);
        	 window.location = ContextPath + "/ProjectList.do?action=main";
            //var loginTitleDIV = document.getElementById("login_title");
            //loginTitleDIV.innerHTML = "Hello " + document.getElementById("username").value + " !";
         }
         else
         {
        	resetLoginForm();
            loginDlg.show();
            var errorDIV = document.getElementById("loginError");
            errorDIV.innerHTML = "Invalid user name or password !!";
         }
      }
      ,
      failure : function(o)
      {
         content.innerHTML = o.responseText;         
         YAHOO.virtium.container.wait.hide();
         var errorDIV = document.getElementById("loginError");
         errorDIV.innerHTML = "CONNECTION FAILED!";
      }
   }
   var postData = "u=" + userName + "&p=" + password;
   showWaitingDialog(sUrl, callback, postData, content);
}

// validate form before login
function checkLoginForm()
{
   if (document.getElementById("username").value == '')
   {
      alert("Enter User Name ");
      document.getElementById("username").focus();
      return false;
   }
   if (document.getElementById("password").value == '')
   {
      alert("Enter password");
      document.getElementById("password").focus();
      return false;
   }

   loginDlg.hide();
   
   //window.location = ContextPath + "/ProjectList.do?action=login&u=" + document.getElementById("username").value +
   	//				"&p=" + document.getElementById("password").value;
   login(document.getElementById("username").value, document.getElementById("password").value);
   return true;
}

function resetLoginForm()
{
	document.getElementById("username").value = '';
	document.getElementById("password").value = '';
}

function showWaitingDialog(sUrl, callback, postData, content)
{
   YAHOO.namespace("virtium.container");

   content.innerHTML = "";
   if ( ! YAHOO.virtium.container.wait)
   {
      // Initialize the temporary Panel to display while waiting for external content to load
      YAHOO.virtium.container.wait = new YAHOO.widget.Panel("wait",
      {
         width : "240px",
         fixedcenter : true,
         close : false,
         draggable : false,
         zindex : 4,
         modal : true,
         visible : false
      }
      );
      YAHOO.virtium.container.wait.setHeader("Loading, please wait...");
      YAHOO.virtium.container.wait.setBody("<img src=\"" + ContextPath + "/images/loading.gif\"/>");
      YAHOO.virtium.container.wait.render(document.body);

   }



   // Show the Panel
   YAHOO.virtium.container.wait.show();


   var conn = YAHOO.util.Connect.asyncRequest("POST", sUrl, callback, postData);
}

function createListTable(o)
{
   formatDateInDataTable = function(elCell, oRecord, oColumn, oData)
   {
  		var oDate = oData;
		var o = typeof(oData);
		if ( o == 'string'){
			oDate = Date.parse(oData);
		}
		var szDate= YAHOO.util.Date.format(new Date(oDate), { format: "%m/%d/%Y"});
		elCell.innerHTML = szDate;
		
	};
	// Add the custom formatter to the shortcuts
	YAHOO.widget.DataTable.Formatter.virtiumDate = formatDateInDataTable;
   var sortPriority = function(a, b, desc)
   {
      // Deal with empty values
      if( ! YAHOO.lang.isValue(a))
      {
         return ( ! YAHOO.lang.isValue(b)) ? 0 : 1;
      }
      else if( ! YAHOO.lang.isValue(b))
      {
         return - 1;
      }

      // First compare by Priority
      var comp = YAHOO.util.Sort.compare;
      var compState = comp(a.getData("Priority"), b.getData("Priority"), desc);

      // If states are equal, then compare by areacode
      return (compState !== 0) ? compState : comp(a.getData("Priority"), b.getData("Priority"), desc);
   }
   ;
   var formatText = function(elCell, oRecord, oColumn, oData)
   {
      elCell.innerHTML = "<pre class=\"address\">" + oData + "</pre>";
   };
   
   /*var previousRow = {};
   dirty = false;   
   resetDirty = function (elRow,oRecord) {
		dirty = false;
		return true;
	};
   // var link_new_majorTaskID = new Array();
   // This is the function doing the groupping.  
	// It is set as a formatter for the DataTable. 
	// It can be set on any or all columns
	grouper = function(elCell, oRecord, oColumn, value) {
		
		var k = oColumn.key,
			// this.getTdEl() doesn't work at this point.  Call it a but or whatever
			td = YAHOO.util.Dom.getAncestorByTagName(elCell,'td');
		
		// if the column should not be grouped, the value is shown 
		// and the style set according to the current row setting
		if (oColumn.group === false) {
			elCell.innerHTML = value;
			YAHOO.util.Dom.addClass(td,(dirty?'first':'next'));
			// It is always important to clear any className previously set.
			YAHOO.util.Dom.removeClass(td,(dirty?'next':'first'));
		} else {
			
			// if the row is dirty (a value changed in a previous column)
			// or the value changed in this very column
			if (dirty || previousRow[k] != value) {
				// mark the remaining columns in the row as dirty
				dirty = true;
				// set the corresponding className
				YAHOO.util.Dom.addClass(td,'first');
				YAHOO.util.Dom.removeClass(td,'next');
				// fill the cell with the value
				elCell.innerHTML = value;
				// save the now current value
				previousRow[k] = value;
			} else {
				// set the style for repeated cells
				YAHOO.util.Dom.addClass(td,'next');
				YAHOO.util.Dom.removeClass(td,'first');
				//Make sure the cell is empty
				elCell.innerHTML = '';
			}
		}
	};*/
   
   var myColumnDefs2 = [
   {
      key : "tableId", sortable : true
   }
   ,
   {
      key : "majorTaskId", sortable : true
   }
   ,
   {
      key : "TypeID", sortable : true
   }
   ,
   {
      key : "UserID", sortable : true
   }
   ,
   {
      key : "Type", sortable : true, sortOptions :
      {
         sortFunction : sortPriority
      }
   }   
   ,{
      key : "Priority", sortable : true, sortOptions :
      {
          sortFunction : sortPriority
       }, editor : new YAHOO.widget.RadioCellEditor(
      {
         radioOptions : [0,1,2,3,4,5]
      })
   }
   ,   
   {
      key : "MajorTask", width : 200, resizeable : true, sortable : true, formatter : formatText, editor : new YAHOO.widget.TextareaCellEditor()
   }
   ,
   {
      key : "Owner", resizeable : true, sortable : true, editor : new YAHOO.widget.RadioCellEditor(
      {
         radioOptions : users
      }
      )
   }
   ,
   {
      key : "StartDate", width : 60, resizeable : true, sortable : true, formatter : YAHOO.widget.DataTable.Formatter.virtiumDate, editor : new YAHOO.widget.DateCellEditor()
   }
   ,
   {
      key : "FinishDate", width : 60, resizeable : true, sortable : true, formatter : YAHOO.widget.DataTable.Formatter.virtiumDate, editor : new YAHOO.widget.DateCellEditor()
   }
   ,
   {
      key : "Cost", width : 30, resizeable : true, sortable : true, formatter : "currency"
   }
   ,
   {
      key : "Achieved", width : 15, resizeable : true, sortable : true, editor : new YAHOO.widget.RadioCellEditor(
      {
         radioOptions : ["Yes", "No"]
      }
      )
   }
   ,
   {
      key : "KeyIssues", resizeable : true, sortable : true, formatter : formatText, editor : new YAHOO.widget.TextareaCellEditor()
   }
   ,
   {
      key : "DecisionNeed", resizeable : true, sortable : true, formatter : formatText, editor : new YAHOO.widget.TextareaCellEditor()
   },
   {
	   key:'delete', label:' ', className:'delete-button'
   } 
   ];
   var response = [];

   try
   {
      response = YAHOO.lang.JSON.parse(o.responseText);
      
      tableObjects = YAHOO.lang.JSON.parse(o.responseText);
   }
   catch(x)
   {
   }
   
   var tables = document.getElementById("tables");
   var i = response.length-1;
   for(i; i >= 0;i--)
   {
   		
   	  //resetDirty();
   	  //previousRow = {};
      // Create DIV
      var newdiv = document.createElement('div');
      var newdiv_temp = document.createElement('div');

      newdiv.setAttribute('id', "table_div_" + i);
      newdiv.innerHTML = 'Element Number';
      newdiv_temp.innerHTML = "<br/><br/><br/><br/><br/>";
      tables.appendChild(newdiv_temp);
      tables.appendChild(newdiv);
      
      //Convert data
      var totalInfo = YAHOO.lang.JSON.parse(response[i]);
      //.purpose  --  .ideaOutcome
      var projectInfor = totalInfo[0][0];
      //var content = YAHOO.lang.JSON.parse(response[i]);
      var content = totalInfo[1];
      	
      var paginator_div = document.createElement('div');
      var projectInfoHTML_1 = "<span><h4><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PURPOSE:&nbsp;</strong><span style=\"background-color: #FFFF00\">" + projectInfor.purpose + "</span></h4></span>";
      var projectInfoHTML_2 = "<span><h4><strong>IDEA OUTCOME:&nbsp;</strong><span style=\"background-color: #FFFF00\">" + projectInfor.ideaOutcome + "</span></h4></span>";
      var table = "<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\"><tr><td rowspan=\"2\"><span><h3><strong>"+ content[0].Type +"</strong></h3></span></td><td>" + projectInfoHTML_1 + "</td></tr><tr><td>" + projectInfoHTML_2 + "</td></tr></table>";            
      paginator_div.innerHTML = table;// + "<br>&nbsp;<span><h3><strong>"+ content[0].Type +"</strong></h3></span>";
      //&nbsp;&nbsp;<span><a id=\"add_new_majorTask_"+i+"\" onClick=\"showNewMajorTaskDlg(event, "+i+"); \" class=\"yui - pg - next\" href=\"#\">Add New</a></span>" + deleteProjectHTML;
      newdiv_temp.appendChild(paginator_div);
      
     
      var myDataTableSource = new YAHOO.util.DataSource(content);
      myDataTableSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
      myDataTableSource.responseSchema =
      {
         fields : ["tableId", "majorTaskId", "TypeID", "UserID", "Type",
         { 
        	 key : "Priority", parser : "int" 
         }
         , "MajorTask", "Owner",
         {
            key : "StartDate", parser : "date"
         }
         ,
         {
            key : "FinishDate", parser : "date"
         }
         , "Cost", "Achieved", "KeyIssues", "DecisionNeed"]
      }
      ;

      var myPaginator = new YAHOO.widget.Paginator(
      {
         rowsPerPage : 10,
         template : YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE,
         rowsPerPageOptions : [10, 25, 50, 100],
         pageLinks : 5
      }
      );
      var myConfigs =
      {
         sortedBy :
         {
            key : "Priority", dir : "asc"
         }
         ,
         paginator : myPaginator,
         draggableColumns : true
      }	  
      	
      // Create DataTable
      var myDataTable = new YAHOO.widget.DataTable(newdiv, myColumnDefs2, myDataTableSource, myConfigs);
      myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
      myDataTable.subscribe("cellDblclickEvent", myDataTable.onEventShowCellEditor);
      myDataTable.subscribe("editorBlurEvent", myDataTable.onEventSaveCellEditor);

      myDataTable.hideColumn(0);
      myDataTable.hideColumn(1);
      myDataTable.hideColumn(2);
      myDataTable.hideColumn(3);
      myDataTable.hideColumn(4);
      tableObjects[i] = myDataTable;

      var paginator_div = document.createElement('div');
      var editProjectHTML = "&nbsp;&nbsp;<span><a id=\"edit_project"+i+"\" onClick=\"showEditProject(event, "+i+"); \" class=\"yui - pg - next\" href=\"#\">EDIT PROJECT</a></span>";
      var deleteProjectHTML = "&nbsp;&nbsp;<span><a id=\"delete_project"+i+"\" onClick=\"deleteProject(event, "+i+"); \" class=\"yui - pg - next\" href=\"#\">DELETE RPOJECT</a></span>";
      var email_archived = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +      						      						
      						"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span><input id=\"pro_mail_"+i+"\" type=\"hidden\" value=\""+projectInfor.email+"\" /><a href=\"mailto:" + projectInfor.email+ "\">EMAIL PROJECT REPORT</a>&nbsp;&nbsp;&nbsp;<input id=\"pro_archived_"+i+"\" type=\"hidden\" value=\""+projectInfor.archived+"\" /><a href=\"" + projectInfor.archived+ "\">ARCHIVE PROJECT</a></spam>";
      paginator_div.innerHTML = "<br>&nbsp;&nbsp;<span><a id=\"add_new_majorTask_"+i+"\" onClick=\"showNewMajorTaskDlg(event, "+i+"); \" class=\"yui - pg - next\" href=\"#\">NEW MAJOR TASK</a></span>" + deleteProjectHTML + email_archived;
      myDataTable.appendChild(paginator_div);

      // When cell is edited, pulse the color of the row yellow
      var onCellEdit = function(oArgs)
      {
      	var elCell = oArgs.editor.getTdEl();
    	var elRow = this.getTrEl(elCell);
      	var oOldData = oArgs.oldData;
        var oNewData = oArgs.newData;

         // Grab the row el and the 2 colors
         
         var origColor = YAHOO.util.Dom.getStyle(elRow.cells[0], "backgroundColor");
         var pulseColor = "#ff0";

         // Create a temp anim instance that nulls out when anim is complete
         var rowColorAnim = new YAHOO.util.ColorAnim(elRow.cells,
         {
            backgroundColor :
            {
               to:origColor, from:pulseColor
            }
            , duration:2
         }
         );
         var onComplete = function()
         {
            rowColorAnim = null;
            YAHOO.util.Dom.setStyle(elRow.cells, "backgroundColor", "");
         }
         rowColorAnim.onComplete.subscribe(onComplete);
         rowColorAnim.animate();
      	if(count == 0)
         {
      		var projectID,majorTaskId,UserID,Type,priority,MajorTask,Owner,StartDate,FinishDate,Cost,Achieved,KeyIssues,DecisionNeed;
      		if(IE){
      			projectID = elRow.cells[0].innerText;
                majorTaskId = elRow.cells[1].innerText;
                UserID = elRow.cells[3].innerText;
                Type = elRow.cells[4].innerText;
                priority = elRow.cells[5].innerText;
                MajorTask = elRow.cells[6].innerText;
                Owner = elRow.cells[7].innerText;
                StartDate = elRow.cells[8].innerText;
                FinishDate = elRow.cells[9].innerText;
                Cost = elRow.cells[10].innerText;
                Achieved = elRow.cells[11].innerText;
                KeyIssues = elRow.cells[12].innerText;
                DecisionNeed = elRow.cells[13].innerText;
      		}else{
      			projectID = elRow.cells[0].textContent;
                majorTaskId = elRow.cells[1].textContent;
                UserID = elRow.cells[3].textContent;
                Type = elRow.cells[4].textContent;
                priority = elRow.cells[5].textContent;
                MajorTask = elRow.cells[6].textContent;
                Owner = elRow.cells[7].textContent;
                StartDate = elRow.cells[8].textContent;
                FinishDate = elRow.cells[9].textContent;
                Cost = elRow.cells[10].textContent;
                Achieved = elRow.cells[11].textContent;
                KeyIssues = elRow.cells[12].textContent;
                DecisionNeed = elRow.cells[13].textContent;
      		}
            
            var h=0;
            for(h=0;h<document.getElementById("selectUser").options.length;h++){
            	if(Owner == document.getElementById("selectUser").options[h].text){
            		UserID = document.getElementById("selectUser").options[h].value;
            	}
            }
            

            var postData = "cost=" + Cost +
            "&majorTask=" + MajorTask +
            "&keyIssues=" + KeyIssues +
            "&userID=" + UserID +
            "&priority=" + priority +
            "&achived=" + Achieved +
            "&startDate=" + StartDate +
            "&finishDate=" + FinishDate +
            "&decision=" + DecisionNeed +
            "&projectID=" + projectID +
            "&majorTaskId=" + majorTaskId;
            count++;
            UpdateMojarTask(postData,oArgs,elCell,elRow);
         }
         else{
          count++ ;
          if(count == tableObjects.length) count =0;
         }
         
         

      }
      myDataTable.subscribe("editorSaveEvent", onCellEdit);
      
      myDataTable.subscribe('cellClickEvent',function(oArgs) {
    	    var target = oArgs.target;
    	    var column = this.getColumn(target);
    	    if (column.key == 'delete') {
    	        if (confirm('Are you sure?')) {
    	            var record = this.getRecord(target);
    	            var postData = "id=" + record.getData('majorTaskId');
    	            var sUrl = ContextPath + "/ProjectList.do?action=deleteMajorTask";
    	            YAHOO.util.Connect.asyncRequest(
    	                    'POST',
    	                    sUrl,
    	                    {
    	                        success: function (o) {
    	                            if (o.responseText == 'Ok') {
    	                                this.deleteRow(target);
    	                            } else {
    	                                alert(o.responseText);
    	                            }
    	                        },
    	                        failure: function (o) {
    	                            alert(o.statusText);
    	                        },
    	                        scope:this
    	                    },
    	                    postData
    	                ); 
    	        }
    	    }
    	});
   }


   YAHOO.virtium.container.wait.hide();
}

function createEditor()
{
   // Start Create Editor
   var myEditorConfig =
   {
      height : '100px',
      width : '300px',
      dompath : true,
      focusAtStart : false
   }
   ;

   myEditor_MajorTask = new YAHOO.widget.SimpleEditor('editor_majorTask', myEditorConfig );
   myEditor_MajorTask.render();

   myEditor_keyIssues = new YAHOO.widget.SimpleEditor('editor_keyIssues', myEditorConfig );
   myEditor_keyIssues.render();

   myEditor_decision = new YAHOO.widget.SimpleEditor('editor_decision', myEditorConfig );
   myEditor_decision.render();
   
   myEditor_prMajorTask = new YAHOO.widget.SimpleEditor('prEditor_majorTask', myEditorConfig );
   myEditor_prMajorTask.render();

   myEditor_PrkeyIssues = new YAHOO.widget.SimpleEditor('prEditor_keyIssues', myEditorConfig );
   myEditor_PrkeyIssues.render();
   
   myEditor_Prdecision = new YAHOO.widget.SimpleEditor('prEditor_decision', myEditorConfig );
   myEditor_Prdecision.render();

   myEditor_Purpose = new YAHOO.widget.SimpleEditor('prPurpose', myEditorConfig );
   myEditor_Purpose.render();
   
   myEditor_IdeaOutcome = new YAHOO.widget.SimpleEditor('prIdeaOutcome', myEditorConfig );
   myEditor_IdeaOutcome.render();
   
   // End Create Editor
}

var showNewMajorTaskDlg = function(e, tableIndex)
{
	var table = tableObjects[tableIndex];
	var projectID = 0;
	if(IE){
		projectID = table.getRow(0).cells[0].innerText;
		document.getElementById("txtTypeNewMajorTask").value =table.getRow(0).cells[4].innerText; 
		document.getElementById("txtTypeNewMajorTaskID").value =table.getRow(0).cells[2].innerText;
	}else{
		projectID = table.getRow(0).cells[0].textContent;
		document.getElementById("txtTypeNewMajorTask").value =table.getRow(0).cells[4].textContent; 
		document.getElementById("txtTypeNewMajorTaskID").value =table.getRow(0).cells[2].textContent;
	}
	document.getElementById("tableIndex").value = tableIndex;
   document.getElementById("projectID").value = projectID;
   
   
   //txtTypeNewMajorTask
   YAHOO.util.Event.stopEvent(e);
   AddNewMajorDialog.show();
};

var deleteProject = function(e, tableIndex){
	if (confirm('Are you sure?')){
	   var table = tableObjects[tableIndex];
	   var projectID = 0;
	   if(IE){
		   projectID = table.getRow(0).cells[0].innerText;
		}else{
			projectID = table.getRow(0).cells[0].textContent;
		}
	   
	   var postData = "id=" + projectID;
	
	   var content = document.getElementById("content");
	   var sUrl = ContextPath + "/ProjectList.do?action=deleteProject";
	   // Define the callback object for Connection Manager that will set the body of our content area when the content has loaded
	   var callback =
	   {
	      success : function(o)
	      {  
	         location.reload(true);
	      }
	      ,
	      failure : function(o)
	      {
	         content.innerHTML = o.responseText;
	         content.style.visibility = "visible";         
	         YAHOO.virtium.container.wait.hide();
	         var errorDIV = document.getElementById("newMajorTaskError");
	         errorDIV.innerHTML = "CONNECTION FAILED!";
	      }
	   }
	
	   showWaitingDialog(sUrl, callback, postData, content);
	}
};

var showEditProject = function(e, tableIndex){
};

var showLoginDlg = function(e)
{
	YAHOO.util.Event.stopEvent(e);
	loginDlg.show();
};

function createDialog()
{
      var showNewProjectDlg = function(e)
   {
	   YAHOO.util.Event.stopEvent(e);
	   AddNewProjectDialog.show();
   };

   // Create Login dialog
   YAHOO.util.Dom.removeClass("loginDialog", "inprogress");
   loginDlg = new YAHOO.widget.Dialog("loginDialog",
   {
      width : "40em",
      visible : false,
      modal : true,
      fixedcenter : true,
      constrainToViewport : true
   }
   );
   loginDlg.render();

   // Create Add New MajorTask dialog
   YAHOO.util.Dom.removeClass("AddNewMajorDialog", "inprogress");
   AddNewMajorDialog = new YAHOO.widget.Dialog("AddNewMajorDialog",
   {
      width : "80em",
      visible : false,
      modal : true,
      fixedcenter : false,
      constrainToViewport : true
   }
   );
   AddNewMajorDialog.render();
   
   //create add new project
   //AddNewProject
   YAHOO.util.Dom.removeClass("AddNewVPMProjectDialog", "inprogress");
   AddNewProjectDialog = new YAHOO.widget.Dialog("AddNewVPMProjectDialog",
   {
      width : "80em",
      visible : false,
      modal : true,
      fixedcenter : false,
      constrainToViewport : true
   }
   );
   AddNewProjectDialog.render();
   
   //User Manager
  
   /*YAHOO.util.Dom.removeClass("userManager", "inprogress");
   UserManagerDialog = new YAHOO.widget.SimpleDialog("userManager",
   {
      width : "80em",
      visible : false,
      modal : true,
      fixedcenter : true,
      constrainToViewport : true
   }
   );
   UserManagerDialog.render();*/
   
   // Hook up the SimpleDialog to the link user-manager-link
   YAHOO.util.Event.addListener("member-login-link", "click", showLoginDlg, this, true);
   YAHOO.util.Event.addListener("add_new_project", "click", showNewProjectDlg , this, true);
   //YAHOO.util.Event.addListener("user-manager-link", "click", UserManagerLoadData , this, true);
   //
}

function UserManagerLoadData(){
	var myColumnDefs2 = [
	                     {
	                        key : "id", sortable : true
	                     }
	                     ,
	                     {
	                        key : "password", sortable : true
	                     }
	                     ,
	                     {
	                        key : "fullName", sortable : true
	                     }
	                     ,
	                     {
	                        key : "userName", sortable : true
	                     }
	                     ,
	                     {
	                  	   key:'delete', label:' ', className:'delete-button'
	                     },
	                     {
	                  	   key:'changePassword', label:' ', className:'delete-button'
	                     }
	                    ];
	
	var content = document.getElementById("content");
    // Define the callback object for Connection Manager that will set the body of our content area when the content has loaded
    var callback =
    {
       success : function(o)
       {
    		var response = YAHOO.lang.JSON.parse(o.responseText);
    		var tables = document.getElementById("userManager_content");
    	    var myDataTableSource = new YAHOO.util.DataSource(response);
    	    myDataTableSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
    	    myDataTableSource.responseSchema =
		    {
		       fields : ["id", "password", "fullName", "userName"]
		    };

    	    var myPaginator = new YAHOO.widget.Paginator(
    	      {
    	         rowsPerPage : 10,
    	         template : YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE,
    	         rowsPerPageOptions : [10, 25, 50, 100],
    	         pageLinks : 5
    	      }
    	      );
    	      
    	    var myConfigs =
    	      {
    	         sortedBy :
    	         {
    	            key : "id", dir : "asc"
    	         }
    	         ,
    	         paginator : myPaginator,
    	         draggableColumns : true
    	      }
    	    
    	      // Create DataTable
    	      var myDataTable = new YAHOO.widget.DataTable(tables, myColumnDefs2, myDataTableSource,myConfigs);
    	      myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
    	      myDataTable.subscribe("cellDblclickEvent", myDataTable.onEventShowCellEditor);
    	      myDataTable.subscribe("editorBlurEvent", myDataTable.onEventSaveCellEditor);

    	      myDataTable.hideColumn(0);
    	      myDataTable.hideColumn(1);
    	      
    	      showUserManager();
       }
       ,
       failure : function(o)
       {

       }
    }
	var sUrl = ContextPath + "/ProjectList.do?action=getAllUser";
    var postData = "";
    showWaitingDialog(sUrl, callback, postData, content);
}

function addNewMajorTask()
{
   myEditor_MajorTask.saveHTML();
   myEditor_keyIssues.saveHTML();
   myEditor_decision.saveHTML();
   // var stripHTML = /<\S[^><]*>/g;
   // myEditor_MajorTask.get('textarea').value = myEditor_MajorTask.get('textarea').value.replace(/<br>/gi, '\n').replace(stripHTML, '');
   var type = document.getElementById("txtTypeNewMajorTask").value.toString();
   var typeID = document.getElementById("txtTypeNewMajorTaskID").value.toString();   
   var cost = document.getElementById("txtCost").value.toString();
   var majorTask = document.getElementById("editor_majorTask").value.toString();
   var keyIssues = document.getElementById("editor_keyIssues").value.toString();
   var userID = document.getElementById("selectUser").value.toString();
   var user = document.getElementById("selectUser")[document.getElementById("selectUser").selectedIndex].text;
   var priority = document.getElementById("sPriority").value.toString();
   var achived = "";
   if(document.getElementById("chkAchived").checked)
   {achived = "Yes";}else{achived = "No";}
   var startDate = document.getElementById("startDate").value.toString();
   var finishDate = document.getElementById("finishDate").value.toString();
   var decision = document.getElementById("editor_decision").value.toString();

   var tableIndex = document.getElementById("tableIndex").value;
   var table = tableObjects[tableIndex];
   var projectID = 0;
   if(IE){
	   projectID = table.getRow(0).cells[0].innerText;
	}else{
		projectID = table.getRow(0).cells[0].textContent;
	}
   


   AddNewMajorDialog.hide();

   var postData = "cost=" + cost +
   "&majorTask=" + majorTask +
   "&keyIssues=" + keyIssues +
   "&userID=" + userID +
   "&priority=" + priority +
   "&achived=" + achived +
   "&startDate=" + startDate +
   "&finishDate=" + finishDate +
   "&decision=" + decision +
   "&projectID=" + projectID ;

   var content = document.getElementById("content");
   var sUrl = ContextPath + "/ProjectList.do?action=addNewMajorTask";
   // Define the callback object for Connection Manager that will set the body of our content area when the content has loaded
   var callback =
   {
      success : function(o)
      {
         var newID = o.responseText;
         table.addRow(
         {
            "Cost" : cost,
            "tableId" : projectID,
            "majorTaskId" : newID,
            "TypeID" : typeID,
            "UserID" : userID,
            "Owner" : user,
            "Achieved" : achived,
            "StartDate" : startDate,
            "Type" : type,
            "FinishDate" : finishDate,
            "KeyIssues" : keyIssues,
            "MajorTask" : majorTask,
            "DecisionNeed" : decision,
            "Priority" : priority
         }
         , 0);
         content.style.visibility = "visible";
         YAHOO.virtium.container.wait.hide();
      }
      ,
      failure : function(o)
      {
         content.innerHTML = o.responseText;
         content.style.visibility = "visible";         
         YAHOO.virtium.container.wait.hide();
         var errorDIV = document.getElementById("newMajorTaskError");
         errorDIV.innerHTML = "CONNECTION FAILED!";
      }
   }

   showWaitingDialog(sUrl, callback, postData, content);
}

function addNewProject(){
	myEditor_prMajorTask.saveHTML();
   myEditor_PrkeyIssues.saveHTML();
   myEditor_Prdecision.saveHTML();
   myEditor_Purpose.saveHTML();
   myEditor_IdeaOutcome.saveHTML();
   // var stripHTML = /<\S[^><]*>/g;
   // myEditor_MajorTask.get('textarea').value = myEditor_MajorTask.get('textarea').value.replace(/<br>/gi, '\n').replace(stripHTML, '');
   var typeID = document.getElementById("prSelectProjectType").value.toString();
   var type = document.getElementById("prSelectProjectType")[document.getElementById("prSelectProjectType").selectedIndex].text;
   var cost = document.getElementById("prTxtCost").value.toString();
   var majorTask = document.getElementById("prEditor_majorTask").value.toString();
   var keyIssues = document.getElementById("prEditor_keyIssues").value.toString();
   var userID = document.getElementById("prSelectUser").value.toString();
   var user = document.getElementById("prSelectUser")[document.getElementById("prSelectUser").selectedIndex].text;
   var achived = "";
   if(document.getElementById("prChkAchived").checked)
   {achived = "Yes";}else{achived = "No";}
   var startDate = document.getElementById("prStartDate").value.toString();
   var finishDate = document.getElementById("prFinishDate").value.toString();
   var decision = document.getElementById("prEditor_decision").value.toString();
   var email = document.getElementById("prMail").value.toString();
   var purpose = document.getElementById("prPurpose").value.toString();
   var ideaOutcome = document.getElementById("prIdeaOutcome").value.toString();
   var priority = document.getElementById("prPriority").value.toString();
   
   AddNewMajorDialog.hide();

   var postData = "cost=" + cost +
   "&majorTask=" + majorTask +
   "&keyIssues=" + keyIssues +
   "&userID=" + userID +
   "&achived=" + achived +
   "&priority=" + priority +
   "&startDate=" + startDate +
   "&finishDate=" + finishDate +
   "&decision=" + decision +   
   "&email=" + email +
   "&typeID=" + typeID +
   "&purpose=" + purpose +
   "&ideaOutcome=" + ideaOutcome;

   var content = document.getElementById("content");
   var sUrl = ContextPath + "/ProjectList.do?action=addNewProject";
   // Define the callback object for Connection Manager that will set the body of our content area when the content has loaded
   var callback =
   {
      success : function(o)
      {  
         location.reload(true);
      }
      ,
      failure : function(o)
      {
         content.innerHTML = o.responseText;
         content.style.visibility = "visible";         
         YAHOO.virtium.container.wait.hide();
         var errorDIV = document.getElementById("newMajorTaskError");
         errorDIV.innerHTML = "CONNECTION FAILED!";
      }
   }

   showWaitingDialog(sUrl, callback, postData, content);
}

function UpdateMojarTask(postData,oArgs,elCell,elRow)
{
   var content = document.getElementById("content");
   var sUrl = ContextPath + "/ProjectList.do?action=updateMajorTask";
   // Define the callback object for Connection Manager that will set the body of our content area when the content has loaded
   var callback =
   {
      success : function(o)
      {
      	 content.innerHTML = o.responseText;
         content.style.visibility = "visible";
         YAHOO.virtium.container.wait.hide();
      }
      ,
      failure : function(o)
      {
         content.innerHTML = o.responseText;
         content.style.visibility = "visible";        
         YAHOO.virtium.container.wait.hide();
         var errorDIV = document.getElementById("newMajorTaskError");
         errorDIV.innerHTML = "CONNECTION FAILED!";
      }
   }
	var conn = YAHOO.util.Connect.asyncRequest("POST", sUrl, callback, postData);
   //showWaitingDialog(sUrl, callback, postData, content);
}

function showCalendar(showBtn, dialog, calendar, Dom, Event, value,renderID)
{
   // Lazy Dialog Creation - Wait to create the Dialog, and setup document click listeners, until the first time the button is clicked.
   if ( ! dialog)
   {
      // showCalendar(showBtn, dialog, calendar, Dom, Event );
      // Hide Calendar if we click anywhere in the document other than the calendar
      Event.on(document, "click", function(e)
      {
         var el = Event.getTarget(e);
         var dialogEl = dialog.element;
         if (el != dialogEl && ! Dom.isAncestor(dialogEl, el) && el != showBtn && ! Dom.isAncestor(showBtn, el))
         {
            dialog.hide();
         }
      }
      );

      function resetHandler()
      {
         // Reset the current calendar page to the select date, or
         // to today if nothing is selected.
         var selDates = calendar.getSelectedDates();
         var resetDate;

         if (selDates.length > 0)
         {
            resetDate = selDates[0];
         }
         else
         {
            resetDate = calendar.today;
         }

         calendar.cfg.setProperty("pagedate", resetDate);
         calendar.render();
      }

      function closeHandler()
      {
         dialog.hide();
      }

      dialog = new YAHOO.widget.Dialog("container",
      {
         visible : false,
         context : ["showStartDate", "tl", "bl"],
         buttons : [
         {
            text : "Reset", handler : resetHandler, isDefault : true
         }
         ,
         {
            text : "Close", handler : closeHandler
         }
         ],
         draggable : false,
         close : true
      }
      );
      dialog.setHeader('Pick A Date');
      dialog.setBody('<div id="cal"></div>');
      dialog.render(document.getElementById(renderID));

      dialog.showEvent.subscribe(function()
      {
         if (YAHOO.env.ua.ie)
         {
            // Since we're hiding the table using yui-overlay-hidden, we
            // want to let the dialog know that the content size has changed, when
            // shown
            dialog.fireEvent("changeContent");
         }
      }
      );


      // Lazy Calendar Creation - Wait to create the Calendar until the first time the button is clicked.
      if ( ! calendar)
      {

         /* function handleSelect(type, args, obj) {
         var dates = args[0];
         var date = dates[0];
         var year = date[0], month = date[1], day = date[2];

         Dom.get(value).value = month + "/" + day + "/" + year;
         dialog.hide();
         } */

         calendar = new YAHOO.widget.Calendar("cal",
         {
            iframe : false,          // Turn iframe off, since container has iframe support.
            hide_blank_weeks : true  // Enable, to demonstrate how we handle changing height, using changeContent
         }
         );
         calendar.render();

         // YAHOO.example.calendar.cal.selectEvent.subscribe(handleSelect, YAHOO.example.calendar.cal, true);
         calendar.selectEvent.subscribe(function(type, args, obj)
         {
            if (calendar.getSelectedDates().length > 0)
            {

               /* var selDate = calendar.getSelectedDates()[0];

               // Pretty Date Output, using Calendar's Locale values: Friday, 8 February 2008
               var wStr = calendar.cfg.getProperty("WEEKDAYS_LONG")[selDate.getDay()];
               var dStr = selDate.getDate();
               var mStr = calendar.cfg.getProperty("MONTHS_LONG")[selDate.getMonth()];
               var yStr = selDate.getFullYear(); */
               var dates = args[0];
               var date = dates[0];
               var year = date[0];
               var month = date[1];
               var day = date[2];
               if(month.toString().length == 1) month = "0" + month;
               if(day.toString().length == 1) day = "0" + day;
               Dom.get(value).value = day + "/" + month + "/" + year;
               ;

               // Dom.get(value).value = wStr + ", " + dStr + " " + mStr + " " + yStr;
            }
            else
            {
               Dom.get(value).value = "";
            }
            dialog.hide();
         }
         );

         calendar.renderEvent.subscribe(function()
         {
            // Tell Dialog it's contents have changed, which allows
            // container to redraw the underlay (for IE6 / Safari2)
            dialog.fireEvent("changeContent");
         }
         );
      }

      var seldate = calendar.getSelectedDates();

      if (seldate.length > 0)
      {
         // Set the pagedate to show the selected date if it exists
         calendar.cfg.setProperty("pagedate", seldate[0]);
         calendar.render();
      }

      dialog.show();
   }
}
